package ex2.grammars.factories;

import ex2.Token;
import ic.ast.decl.PrimitiveType;
import ic.ast.expr.Literal;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 11/24/13
 */
public class LiteralFactory {

    /**
     * Creates literal according to token
     * @param token token
     * @return created literal
     */
    public static Literal create(Token token) {
        if(token.tag.equals("null"))
            return new Literal(token.getLine(), PrimitiveType.DataType.VOID, token.getValue());
        else if(token.tag.equals("true") || token.tag.equals("false"))
            return new Literal(token.getLine(), PrimitiveType.DataType.BOOLEAN, token.getValue());
        else if(token.tag.equals("STRING"))
            return new Literal(token.getLine(), PrimitiveType.DataType.STRING, parseStr(token.getValue()));
        else
            throw new Error("Error");
    }

    private static String parseStr(String s) {
        int n = s.length();
        String str = s.substring(1, n - 1);
        if (str.equals("\\n")) {
            str = "\n";
        }
        return str;
    }
}